package svc

import (
	"GoZero/mall/model/api/internal/config"
	"GoZero/mall/model/api/internal/models"
	user "GoZero/mall/user/rpc/userclient"
	"fmt"

	"github.com/zeromicro/go-zero/zrpc"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config  config.Config
	UserRpc user.User
	DB      *gorm.DB
}

func NewServiceContext(c config.Config) *ServiceContext {
	dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		c.Database.Host,
		c.Database.Post,
		c.Database.User,
		c.Database.Password,
		c.Database.Name,
	)
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

	if err != nil {
		panic(err)
	} else {
		fmt.Println("suc")
	}

	db.AutoMigrate(&models.Userinfo{})

	return &ServiceContext{
		Config:  c,
		UserRpc: user.NewUser(zrpc.MustNewClient(c.UserRpc)),
		DB:      db,
	}
}
